const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 })

let userCount = 0
wss.broadcast = function broadcast(msg) {
    wss.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
            client.send(msg);
        }
    });
};
wss.on('connection', function connection(ws) {
    userCount++
    let username = '游客' + userCount
    wss.broadcast(`${username} 进入聊天室`)
    ws.on('message', function incoming(msg) {
        console.log(`${username}: ${msg}`);
        // 将用户的发言广播给所有人。
        wss.broadcast(`${username}: ${msg}`)
    });

    ws.on('close', function leave() {
        wss.broadcast(`${username} 离开聊天室`)
    })
});



